package com.icesoft.core.web.configurer.filter;

import com.icesoft.core.web.configurer.IcesoftSafeProperty;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@AllArgsConstructor
public class HttpHostHeaderFilter implements Filter {

    IcesoftSafeProperty safeProperty;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String serverPath = safeProperty.getHostPath();
        if (StringUtils.isNotBlank(serverPath)) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String host = httpServletRequest.getHeader("host").trim();
            log.trace("host:{}", host);
            if (StringUtils.isBlank(serverPath) || !serverPath.contains(host)) {
                log.warn("refuse error host access, error host={}", host);
                HttpServletResponse res = (HttpServletResponse) response;
                res.setStatus(403);
                return;
            }
        }

        chain.doFilter(request, response);
    }

}
